package com.lp.article.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lp.article.service.ILikeService;
import com.lp.model.config.AppResult;
import com.lp.model.config.CodeMsg;
import com.lp.model.dto.article.LikeDto;
import com.lp.model.dto.article.PageDto;
import com.lp.model.entity.article.redis.LikesMsg;
import com.lp.model.entity.article.redis.vo.LikesMsgVO;
import com.lp.model.entity.article.vo.PageVO;
import com.lp.model.entity.user.User;
import com.lp.model.utils.PageUtils;
import com.lp.model.utils.UserUtils;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/article/like")
public class LikeController {

    @Autowired
    private ILikeService likeService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 点赞/取消点赞
     * @param request 获取用户数据
     * @param likeDto 存放了点赞文章的 id
     */
    @PostMapping("/play")
    public AppResult like(HttpServletRequest request, @RequestBody @NonNull LikeDto likeDto) {
        //1.非空校验
        if(likeDto.getArticleId() == null) {
            return AppResult.fail(CodeMsg.FAIL_NULL_LIKE);
        }
        //2.准备数据
        User userByToken = UserUtils.getUserByToken(redisTemplate, objectMapper, request);
        likeService.like(userByToken.getId(), likeDto);
        return AppResult.success();
    }

    /**
     * 删除该用户的所有点赞消息
     */
    @GetMapping("/del_msg_all")
    public AppResult delMsgAll(HttpServletRequest request) {
        //1.准备用户信息
        User userByToken = UserUtils.getUserByToken(redisTemplate, objectMapper, request);
        Long userId = userByToken.getId();
        likeService.delMsgAll(userId);
        return AppResult.success();
    }

    @PostMapping("/msg_page")
    public AppResult msgPage(HttpServletRequest request, @NonNull @RequestBody PageDto page) {
        //1.非法校验
        if(!PageUtils.checkPageDto(page)) {
            return AppResult.fail(CodeMsg.FAIL_ERROR_PAGE);
        }
        //2.准备用户数据
        User user = UserUtils.getUserByToken(redisTemplate, objectMapper, request);
        page.setId(user.getId());
        PageVO<LikesMsgVO> msgPage = likeService.getMsgPage(page);
        return AppResult.success(msgPage);
    }

    @GetMapping("/is_read")
    public AppResult isRead(HttpServletRequest request) {
        //1.准备用户数据
        User user = UserUtils.getUserByToken(redisTemplate, objectMapper, request);
        boolean read = likeService.isRead(user.getId());
        return AppResult.success(read);
    }

}
